package ynu.edu.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ynu.edu.entity.Cart;
import ynu.edu.service.CartService;
import ynu.edu.service.UserService;
import ynu.edu.dto.CartResponse;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/CartController")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private UserService userService;

    @PostMapping("/listCart")
    public ResponseEntity<?> listCart(@RequestBody Cart params) {
        log.info("Received listCart request with params: {}", params);
        if (params.getUserName() == null) {
            return ResponseEntity.badRequest().body("userName不能为空");
        }
        List<Cart> carts;
        if (params.getBusinessId() != null) {
            carts = cartService.listCartByUserNameAndBusinessId(params.getUserName(), params.getBusinessId());
        } else {
            carts = cartService.listCartByUserName(params.getUserName());
        }
        log.info("Found carts: {}", carts);
        return ResponseEntity.ok(carts);
    }

    @PostMapping("/saveCart")
    public ResponseEntity<?> saveCart(@RequestBody Cart params) {
        log.info("Received saveCart request with params: {}", params);
        if (params.getUserName() == null || params.getBusinessId() == null || params.getFoodId() == null) {
            return ResponseEntity.badRequest().body("userName、businessId和foodId不能为空");
        }
        boolean success = cartService.saveCart(params);
        return ResponseEntity.ok(new CartResponse(success, success ? "保存成功" : "保存失败"));
    }

    @PostMapping("/updateCart")
    public ResponseEntity<?> updateCart(@RequestBody Cart params) {
        log.info("Received updateCart request with params: {}", params);
        if (params.getUserName() == null || params.getBusinessId() == null || 
            params.getFoodId() == null || params.getQuantity() == null) {
            return ResponseEntity.badRequest().body("userName、businessId、foodId和quantity不能为空");
        }
        int result = cartService.updateCart(params);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/removeCart")
    public ResponseEntity<?> removeCart(@RequestBody Cart params) {
        log.info("Received removeCart request with params: {}", params);
        if (params.getUserName() == null || params.getBusinessId() == null) {
            return ResponseEntity.badRequest().body("userName和businessId不能为空");
        }
        int result;
        if (params.getFoodId() != null) {
            result = cartService.removeCartItem(params);
        } else {
            result = cartService.removeCartByBusiness(params);
        }
        return ResponseEntity.ok(result);
    }
} 